﻿

@inject IHttpService _httpService
@inject NavigationManager NavigationManager
@inject IDataCacheService _dataCacheService
@inject IPopupService PopupService


<MDialog @bind-Value="Dialog"
         Width="800">
    <MDCard>
        <MCardTitle Class="text-h5">
            编辑周报
        </MCardTitle>
        <MCardText>
            主页一般情况下留空，会根据包含的动态进行动态解析生成，也可以用特殊语法控制显示
        </MCardText>
        <MCardText>
            @if (isReady)
            {
                <CnGalWebSite.Components.Containers.MasaTitleContainer Icon="@IconType.Home.ToIconString()" Title="正文" Class="mb-4" Collapable Outline OutlineHead>
                     <MRow>
                         <MCol Cols="12" Md="6">
                             <CnGalWebSite.Components.Images.UploadButton ShowCropper @bind-ImagePath="@Model.MainPicture" Type="ImageAspectType._16_9" Text="上传主图" Class="mb-4"/>
                         </MCol>
                         <MCol Cols="12">
                             <MTextField @bind-Value="Model.Title" Label="标题" />
                         </MCol>
                         <MCol Cols="12">
                             <MTextarea Rows="5" @bind-Value="Model.BriefIntroduction" Label="简介" />
                         </MCol>
                         <MCol Cols="12">
                             <MTextarea Rows="5" @bind-Value="Model.MainPage" Label="主页" />
                         </MCol>
                     </MRow>

                </CnGalWebSite.Components.Containers.MasaTitleContainer>
                <CnGalWebSite.Components.Containers.MasaTitleContainer Icon="@IconType.Infor.ToIconString()" Title="基本信息" Class="mb-4" Collapable Outline OutlineHead>
                 <MRow>
                     <MCol Cols="12" Md="6">
                         <CnGalWebSite.Components.Inputs.MasaSelecte @bind-Value="Model.Type" TValue="ArticleType" Label="类别" />
                     </MCol>
                     <MCol Cols="12" Md="6">
                         <CnGalWebSite.Components.Inputs.MasaDatePicker ShowDate ShowTime @bind-Value="Model.PublishTime" Label="原文发布时间" />
                         </MCol>
                     </MRow>
                </CnGalWebSite.Components.Containers.MasaTitleContainer>
                <CnGalWebSite.Components.Containers.MasaTitleContainer Icon="@IconType.Link.ToIconString()" Title="包含的动态" Class="mb-4" Collapable Outline OutlineHead>
                    @foreach (var item in Model.News)
                    {
                        <MCheckbox @bind-Value="item.IsSelected" Label="@($"{item.NewsId}. {item.NewsTitle}")" Class="m-0" ></MCheckbox>
                    }

                    <CnGalWebSite.Components.Buttons.MasaButton Text="重置" IsAsync="true" OnClick="OnReset" Icon="mdi-refresh" Color="error" />

                </CnGalWebSite.Components.Containers.MasaTitleContainer>

            }
            else
            {
                <CnGalWebSite.Components.Progressings.ProgressingCard />
            }

        </MCardText>
        <MCardActions Class="pb-6 pe-6 ps-6 pt-0">
            @if (isReady)
            {
                @if (Model.State == GameNewsState.Edit)
                {
                    <CnGalWebSite.Components.Buttons.MasaButton Text="预览" IsAsync="true" OnClick="OnPreview" Icon="mdi-view-day"  TextStyle/>
                }
                else if (Model.State == GameNewsState.Publish && Model.ArticleId != null)
                {
                    <CnGalWebSite.Components.Buttons.MasaButton Text="查看" IsAsync="true" OnClick="OnLook" Icon="mdi-view-day"  TextStyle/>

                }
            }
            <MSpacer></MSpacer>
            @if (Model.State == GameNewsState.Edit)
            {
                <CnGalWebSite.Components.Buttons.MasaButton Text="发布" IsAsync="true" OnClick="OnPublish" Icon="mdi-publish" Class="me-2" Rounded />

            }


            <CnGalWebSite.Components.Buttons.MasaButton Text="保存" IsAsync="true" OnClick="OnSave" Icon="mdi-check" Color="success" Rounded />
        </MCardActions>
    </MDCard>
</MDialog>

<PreviewArticleTip @ref="previewArticleTip" />

@code {
    [Parameter]
    public EventCallback OnRefreshTable { get; set; }

    private long Id { get; set; }


    private EditWeeklyNewsModel Model { get; set; } = new EditWeeklyNewsModel();

    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }

    bool isReady = false;
    bool Dialog { get; set; }

    private List<string> GameNewsValue { get; set; } = new List<string>();

    PreviewArticleTip previewArticleTip;

    private async Task Init()
    {
        try
        {
            Model = await _httpService.GetAsync<EditWeeklyNewsModel>("api/news/EditWeeklyNews/" + Id);


            isReady = true;
            StateHasChanged();
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, "获取编辑周报信息失败");
        }
    }

    public async Task DataChanged()
    {
        isReady = false;
        StateHasChanged();
        await Init();
        await OnRefreshTable.InvokeAsync();

    }

    public async Task OnSave()
    {
        //上传
        try
        {
            //处理数据
            if (Model.News.Any(s => s.IsSelected) == false)
            {
                await PopupService.ToastErrorAsync("保存周报数据失败", "至少选中一个动态");
                return;
            }

            var obj = await _httpService.PostAsync<EditWeeklyNewsModel, Result>("api/news/EditWeeklyNews", Model);
            //判断结果
            if (obj.Successful == false)
            {
                await PopupService.ToastErrorAsync("保存周报数据失败", obj.Error);
            }
            else
            {
                await DataChanged();
                await PopupService.ToastSuccessAsync("保存周报数据成功", "保存周报数据成功");
            }
        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, "保存周报数据失败");
        }
    }


    public async Task OnPublish()
    {
        //先保存
        await OnSave();
        try
        {
            var result = await _httpService.GetAsync<Result>("api/news/PublishWeelyNews/" + Id);
            if (result.Successful)
            {
                await PopupService.ToastSuccessAsync("发布周报成功", "发布周报成功");
                Dialog = false;
            }
            else
            {
                await PopupService.ToastErrorAsync("发布周报失败", result.Error);
            }

        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, "发布周报失败");
        }

    }


    public async Task OnPreview()
    {

        try
        {
            ArticleViewModel model = await _httpService.GetAsync<ArticleViewModel>("api/news/GetWeelyNewsPreview/" + Id);


            if (previewArticleTip != null)
            {
                previewArticleTip.Refresh(true, model);
            }

        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, "获取周报预览数据失败");
        }

    }

    private async Task OnLook()
    {
        Dialog = false;
        NavigationManager.NavigateTo("/articles/index/" + Model.ArticleId);

    }
    public async Task OnReset()
    {
        try
        {
            var result = await _httpService.GetAsync<Result>("api/news/ResetWeelyNews/" + Id);
            if (result.Successful)
            {
                await DataChanged();
                await PopupService.ToastSuccessAsync("重置周报成功", "重置周报成功");

            }
            else
            {
                await PopupService.ToastErrorAsync("重置周报失败", result.Error);
            }

        }
        catch (Exception ex)
        {
            await ErrorHandler.ProcessError(ex, "重置周报失败");
        }

    }

    public async Task Refresh( long id)
    {
        Dialog = true;
        Id = id;
        isReady = false;

        StateHasChanged();

        await Init();

        StateHasChanged();
    }

}
